#!/usr/bin/env node

const Koa = require('koa'),
      bodyparser = require('koa-bodyparser'),
      task = require('./routes/task.js'),
      json = require('koa-json'),
      jwt = require('koa-jwt'),
      jwt2 = require('jsonwebtoken'),
      logger = require('koa-logger'),
      { JWT_KEY } = require('./lib/constant.js'),
      users = require('./routes/users');
      
const app = new Koa();



app.use(json());
app.use(logger());
app.use(jwt({ secret: JWT_KEY }).unless({ path: /\/api\/users\/login$/ }));
app.use(bodyparser({ enableTypes: ['json', 'form', 'text'] }));
app.use(async(ctx, next) => {

  let token = ctx.headers.authorization;
  
  if(typeof token !== 'undefined'){
    token = token.split(' ')[1];
    let user = jwt2.verify(token, JWT_KEY);
    console.log(user);
    ctx.userId = user.id;
  }


  await next();
});
app.use(task.routes());
app.use(users.routes());

app.listen(8080);

